//
//  DDTabEncryptionVC.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/6/28.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDTabEncryptionVC.h"
#import "DDNetWorkAPIClient.h"
#import "DDTabEncryptionHDVC.h"
#import "XHTwitterPaggingViewer.h"
#import "DDTabQuestionScrollerVC.h"
#import "TNColorScrollViewController.h"
#import "DDQuestionView.h"
#import "DDTagVC.h"
#import "DDTagDB.h"
#import "TAPageControl.h"
#import "DDBanner.h"
#import "testScrollViewViewControllerViewController.h"
#import "TOWebViewController.h"
#import "DDQuestionsRootVC.h"
@interface DDTabEncryptionVC ()
{
    XHTwitterPaggingViewer *twitterPaggingViewer;
}
@property (weak, nonatomic) IBOutlet UITextField *passwordInputTextFiled;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;

@property (weak, nonatomic) IBOutlet UIImageView *topBgView;
@property (nonatomic,strong) DDTopicDataCellModel *model;
@property (nonatomic,strong) NSArray *questions;

@property (nonatomic, strong) TNColorScrollViewController *colorScrollVC;

@property (weak, nonatomic) IBOutlet UIView *topView;
@end

@implementation DDTabEncryptionVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    [self createData];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - private
- (void)createUI
{
    self.passwordInputTextFiled.layer.cornerRadius = 10.0;
    self.passwordInputTextFiled.layer.borderColor = RGB(42, 172, 226).CGColor;
    self.passwordInputTextFiled.layer.borderWidth = 1.0;
    self.navigationController.navigationBar.hidden = YES;
    
    self.confirmButton.layer.cornerRadius = 5.0;
    
    
}
- (void)createData
{
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(popTagView:) name:@"popTagView" object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(clearPopTagView) name:@"clearTagView" object:nil];

    __weak DDTabEncryptionVC *weakSelf = self;
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
    [network adList:@{@"positionCode":@"index-banner"} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        NSLog(@"%@",object);
        
        NSError *error;
        DDBanner *banner = [[DDBanner alloc] initWithDictionary:object error:&error];
        if (error) {
            NSLog(@"%@",error.userInfo);
        }
        NSArray *list = banner.data;
        NSMutableArray *temp = [NSMutableArray array];
        for (DDBannerCell *banner in list) {
            [temp addObject:banner.url];
        }
        testScrollViewViewControllerViewController *test = [[testScrollViewViewControllerViewController alloc] initWithNibName:@"testScrollViewViewControllerViewController" bundle:nil];
        [weakSelf addChildViewController:test];
        test.images = temp;
        test.tapView = ^(NSInteger index){
            DDBannerCell *bannerModel = [list objectAtIndex:index];
            TOWebViewController *web = [[TOWebViewController alloc] initWithURLString:bannerModel.linkUrl];
            web.hidesBottomBarWhenPushed =YES;
            web.hideWebViewBoundaries = YES;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoVC" object:web];
        };
        test.view.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [weakSelf.view addSubview:test.view];
        
    }];
    
}

-(void)clearPopTagView
{
    [[self.colorScrollVC.view viewWithTag:10001] removeFromSuperview];
}
- (void)popTagView:(NSNotification *)note
{
    
    UIView *view = [self.colorScrollVC.view viewWithTag:10001];
    if (view) {
        [self clearPopTagView];
        return;
    }
    
    DDTagVC * _tagVC = [[DDTagVC alloc] initWithNibName:@"DDTagVC" bundle:nil];
    [self.colorScrollVC addChildViewController:_tagVC];
    NSDictionary *dict = note.object;
    _tagVC.x = [dict objectForKey:@"x"];
    _tagVC.y = [dict objectForKey:@"y"];
    _tagVC.index = [dict objectForKey:@"index"];
    _tagVC.qid = [dict objectForKey:@"qid"];
    _tagVC.page = [dict objectForKey:@"page"];
    CGRect rect = _tagVC.view.frame;
    _tagVC.view.frame = CGRectMake((self.colorScrollVC.view.frame.size.width-rect.size.width)/2, self.view.frame.size.height, rect.size.width, rect.size.height);
    _tagVC.view.tag = 10001;
    [self.colorScrollVC.view addSubview:_tagVC.view];
    _tagVC.view.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _tagVC.view.frame = CGRectMake((self.colorScrollVC.view.frame.size.width-rect.size.width)/2, self.colorScrollVC.view.frame.size.height/2, rect.size.width, rect.size.height);
    }];
    
    int selectPage = (int)_tagVC.page.integerValue - 1;
    __weak DDTabEncryptionVC *weakSelf = self;
    _tagVC.result = ^(NSString *result,id object,NSString *type)
    {
        NSArray *views = weakSelf.colorScrollVC.view.scrollView.subviews;
        if (views.count > 0) {
            DDQuestionView *qview = views[selectPage];
            [qview.tableView reloadData];
        }
    };
}


- (IBAction)confirmAction:(id)sender {
    NSDictionary *params = @{@"type":@"1",@"password":_passwordInputTextFiled.text};
    DDNetWorkAPIClient *netwrok = [[DDNetWorkAPIClient alloc]init];
    [MBProgressHUD showMessag:@"正在加载..." toView:self.view];
    [netwrok mainTopicList:params completionBlock:^(BOOL isSuccess, NSString *message, NSString *status,id object) {
        DDTopic *topic = object;
        if (object&&topic.list.count>0) {
            _model = topic.list[0];
            _questions = _model.questions;
            NSMutableArray *qustionViews = [NSMutableArray array];
            for (int i = 0; i < _questions.count; i++)
            {
                DDTopicQuestion *question = _questions[i];
                TNColorViewData *viewData = [[TNColorViewData alloc] initWithCustomClass:[DDQuestionView class]];
                viewData.question = question;
                viewData.page = i+1;
                
                BOOL show = NO;
                if (_model.showAnswer&&[_model.showAnswer isEqualToString:@"1"]) {
                    show = YES;
                }
                
                viewData.showAnswer = show;
                viewData.total = _questions.count;
                [qustionViews addObject:viewData];
                
            }
            TNColorScrollViewConfig *config = [[TNColorScrollViewConfig alloc] initWithColorDataObjects:qustionViews bounces:YES showsHorizontalScrollIndicator:NO showsVerticalScrollIndicator:NO pagingEnabled:YES scrollHorizontal:YES];
            
            self.colorScrollVC = [[TNColorScrollViewController alloc] initWithColorScrollViewConfig:config displayMedia:YES cssStyle:DDCSSStyleAnswer];
            self.colorScrollVC.topicID = _model.id;
            self.colorScrollVC.topicType = @"1";
            self.colorScrollVC.topic = _model;
            self.colorScrollVC.showAnswer = _model.showAnswer;
            //self.colorScrollVC.isDisplayMedia = YES;
            self.colorScrollVC.currentScrollerPage = ^(NSInteger currentPage){
                NSLog(@"%ld",(long)currentPage);
            };
            __weak DDTabEncryptionVC *weakSelf = self;
            self.colorScrollVC.preScrollerPage = ^(NSInteger prePage){
                // NSLog(@"%d",prePage);
                DDNetWorkAPIClient *netwrok = [[DDNetWorkAPIClient alloc]init];
                DDTopicQuestion *question = weakSelf.questions[prePage];
                //NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                //NSString *result = [userDefault objectForKey:@"result"];
                DDQuestionView *questionView =  weakSelf.colorScrollVC.view.scrollView.subviews[prePage];
                NSString *result = questionView.result;
                
                
    
                
                //答案集合上传
                NSString *explanationJson = @"";
                NSArray *answers = questionView.answers;
                NSMutableArray *explanations = [NSMutableArray array];
                
                NSString *answerString = @"";
                if ([questionView.questionType isEqualToString:@"填空题"] || [questionView.questionType isEqualToString:@"简答题"]) {
                    NSDictionary *pngDict = @{@"type":@"TEXT",@"text":questionView.result?questionView.result:@"",@"url":@""};
                    [explanations addObject:pngDict];
                }else{
                    answerString = questionView.result?questionView.result:@"";
                }

                
                for (int i = 0; i < answers.count ; i++) {
                    NSString *ext = [answers[i] pathExtension];
                    if ([ext isEqualToString:@"jpg"]) {
                        //                    NSDictionary *pngDict = @{@"type":@"IMAGE",@"url":answers[i]};
                        //                    [explanations addObject:pngDict];
                        //保存泡泡标签
                        NSArray *tags =   [DDTagDB searchWithWhere:[NSString stringWithFormat:@"qid='%@' ",questionView.question.id] orderBy:nil offset:0 count:0];
                        NSMutableArray *filterArray = [NSMutableArray array];
                        for (int i = 0; i < tags.count; i++) {
                            DDTagDB *tag = tags[i];
                            if (![filterArray containsObject:tag.tagIndex]) {
                                [filterArray addObject:tag.tagIndex];
                            }
                            
                        }
                        NSArray *sortArray = [NSArray arrayWithArray:filterArray];
                        [sortArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                            
                            NSString *o1 = (NSString *)obj1;
                            NSString *o2 = (NSString *)obj2;
                            if ([o1 integerValue] > [o2 integerValue]) {
                                return NSOrderedAscending;
                            }
                            if ([o1 integerValue] < [o2 integerValue]) {
                                return NSOrderedDescending;
                            }
                            return NSOrderedSame;
                        }];
                        
                        if (sortArray.count > i) {
                            NSArray *tagss =   [DDTagDB searchWithWhere:[NSString stringWithFormat:@"qid='%@' AND tagIndex='%@'",questionView.question.id,sortArray[i]] orderBy:nil offset:0 count:0];
                            
                            NSMutableArray *tagLabels = [NSMutableArray array];
                            
                            for (DDTagDB *tagdb in tagss) {
                                if ([tagdb.type isEqualToString:@"IMAGE"]||[tagdb.type isEqualToString:@"AUDIO"]) {
                                    NSDictionary *dict = @{@"type":[tagdb.type isEqualToString:@"AUDIO"]?@"VOICE":tagdb.type,@"x":[NSNumber numberWithInteger:[tagdb.x integerValue]],@"y":[NSNumber numberWithInteger:[tagdb.y integerValue]],@"url":tagdb.result};
                                    [tagLabels addObject:dict];
                                }else if ([tagdb.type isEqualToString:@"TEXT"]){
                                    NSDictionary *dict = @{@"type":tagdb.type,@"x":[NSNumber numberWithInteger:[tagdb.x integerValue]],@"y":[NSNumber numberWithInteger:[tagdb.y integerValue]],@"text":tagdb.result};
                                    [tagLabels addObject:dict];
                                }
                            }
                            NSDictionary *pngDict = @{@"type":@"IMAGE",@"url":answers[i],@"labels":tagLabels};
                            [explanations addObject:pngDict];
                            
                        }
                        
                        
                    }
                    if ([ext isEqualToString:@"caf"]) {
                        NSDictionary *cafDict = @{@"type":@"VOICE",@"url":answers[i]};
                        [explanations addObject:cafDict];
                    }
                    
                }
                
                NSError *error;
                NSData * JSONData = [NSJSONSerialization dataWithJSONObject:explanations
                                                                    options:kNilOptions
                                                                      error:&error];
                explanationJson = [[NSString alloc]initWithData:JSONData encoding:NSUTF8StringEncoding];
                
                
                [netwrok mainAnswerSave:@{@"topicId":weakSelf.model.id,@"qid":question.id,@"answer":answerString,@"costSeconds":@"10",@"explanation":explanationJson} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
                    NSLog(@"%@",object);
                    if (object) {
                        
                    }
                    [MBProgressHUD showMessag:message toView:weakSelf.view];
                    
                }];
            };
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:self.colorScrollVC];
            weakSelf.passwordInputTextFiled.text = @"";
        }else{
            [MBProgressHUD showMessag:@"没有找到加密题" toView:self.view];
        }
    }];
}

- (IBAction)question:(id)sender {
//    DDQuestionsRootVC *questionVC = [[DDQuestionsRootVC alloc]initWithNibName:@"DDQuestionsRootVC" bundle:nil];
//    [self presentViewController:questionVC animated:YES completion:nil];
    
    DDQuestionsRootVC *questionVC = [[DDQuestionsRootVC alloc]initWithNibName:@"DDQuestionsRootVC" bundle:nil];
    
    //[self.navigationController pushViewController:collectionVC animated:YES];
    questionVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:questionVC animated:YES];
}






- (IBAction)cancelKeyBoard:(id)sender {
    [self.passwordInputTextFiled resignFirstResponder];
}



@end
